<script setup lang="ts">
  import { ElForm, ElFormItem, ElSelect, ElOption, ElOptionGroup } from 'element-plus'
  import { useConnectServiceModality } from '@/services/pages/good/useGood'
  import { computed, PropType, ref, watch } from 'vue'
  import { useGetModuleOptions as useGetOrderModuleOptionList } from '@/services/pages/order/useModule'
  import { useGetOptions as useGetReturnFactoryModuleOptionList } from '@/services/pages/return-factory/useModule'
  import _ from 'lodash'
  import { HMessage, HMessageBox } from '@/components/common/message'

  const {
    options: orderModuleOptionList,
    getOptionsLoading: getOrderModuleOptionListLoading,
    getOptionsKeyword: getOrderModuleOptionListKeyword,
    getOptions: getOrderModuleOptionList,
  } = useGetOrderModuleOptionList()
  const {
    options: returnFactoryModuleOptionList,
    getOptionsLoading: getReturnFactoryModuleOptionListLoading,
    getOptionsParam: getReturnFactoryModuleOptionParam,
    getOptions: getReturnFactoryModuleOptionList,
  } = useGetReturnFactoryModuleOptionList()
  const { connectLoading, connectForm, connect, resetForm } = useConnectServiceModality()

  defineOptions({
    name: 'GOodServiceModalityConnectModal',
  })

  const props = defineProps({
    productIds: {
      type: Array as PropType<Array<string>>,
      required: true,
    },
    defaultSelectIdList: {
      type: Array as PropType<Array<string>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 服务形式选中列表
  const serviceModalitySelectIdList = ref<Array<string>>([])

  // 服务形式下拉选项
  const serviceFormOptionList = computed(() => {
    return [
      {
        label: '工单模块',
        options: orderModuleOptionList.value.map((item) => {
          return {
            label: item.name,
            value: item.id,
            type: 1,
            disabled: item.disabled,
          }
        }),
      },
      {
        label: '返厂模块',
        options: returnFactoryModuleOptionList.value.map((item) => {
          return {
            label: item.name,
            value: item.id,
            type: 2,
            disabled: item.disabled,
          }
        }),
      },
    ]
  })

  /**
   * 获取服务形式下拉选项
   * @param keyword - 搜索关键字
   */
  const handleGetServiceFormOptionList = _.debounce((keyword: string) => {
    if (getOrderModuleOptionListKeyword.value !== keyword) {
      getOrderModuleOptionListKeyword.value = keyword
      getOrderModuleOptionList()
    }

    if (getReturnFactoryModuleOptionParam.value.name !== keyword) {
      getReturnFactoryModuleOptionParam.value.name = keyword
      getReturnFactoryModuleOptionList()
    }
  }, 600)

  /**
   * 服务形式选择事件
   */
  const handleServiceFormChange = (moduleIdList: Array<string>) => {
    connectForm.value.productModuleRelationVos = moduleIdList.map((moduleId) => {
      const orderModule = orderModuleOptionList.value.find((module) => module.id === moduleId)
      const returnModule = returnFactoryModuleOptionList.value.find(
        (module) => module.id === moduleId,
      )
      if (orderModule || returnModule) {
        return {
          moduleId,
          type: orderModule ? 1 : 2,
        }
      }
    })
  }

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    visible.value = false
    resetForm()
  }

  /**
   * 确定事件
   */
  const onConfirm = async () => {
    if (serviceModalitySelectIdList.value.length > 0) {
      const res = await connect()
      if (res.code === 20000) {
        HMessage.success('关联成功')
        hideDialog()
        emits('update')
        return
      }
      HMessageBox.error(res.message)
    }
  }

  watch(visible, (value) => {
    if (value) {
      connectForm.value.productIds = props.productIds
      serviceModalitySelectIdList.value = props.defaultSelectIdList
      getReturnFactoryModuleOptionList()
      getOrderModuleOptionList()
    }
  })
</script>

<template>
  <h-dialog v-model="visible" title="服务形式关联" :loading="connectLoading" @close="hideDialog">
    <el-form label-position="top" class="modal_form_content" :model="connectForm">
      <el-form-item label="服务形式">
        <el-select
          v-model="serviceModalitySelectIdList"
          multiple
          collapse-tags
          collapse-tags-tooltip
          :loading="getOrderModuleOptionListLoading || getReturnFactoryModuleOptionListLoading"
          :max-collapse-tags="3"
          placeholder="请选择服务形式"
          filterable
          :filter-method="handleGetServiceFormOptionList"
          @change="handleServiceFormChange"
        >
          <el-option-group
            v-for="(group, groupIndex) in serviceFormOptionList"
            :key="groupIndex"
            :label="group.label"
          >
            <el-option
              v-for="(option, optionIndex) in group.options"
              :key="optionIndex"
              :value="option.value"
              :label="option.label"
              :disabled="option.disabled"
            >
              <div style="padding-left: 10px; box-sizing: border-box">{{ option.label }}</div>
            </el-option>
          </el-option-group>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>

<style scoped lang="scs"></style>
